﻿using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace LSA.Framework
{
    public class BulgarianStemmer
    {
        private Dictionary<string, string> stemmingRules;
        private const int STEM_BOUNDARY = 1;

        public BulgarianStemmer(string fileName)
        {
            stemmingRules = new Dictionary<string, string>();

            using (StreamReader stream = File.OpenText(fileName))
            {
                string line;
                while ((line = stream.ReadLine()) != null)
                {
                    Match match = Regex.Match(line, @"([а-я]+)\s==>\s([а-я]+)\s([0-9]+)", RegexOptions.Compiled);
                    if (match.Success)
                    {
                        if (match.Groups.Count == 4)
                        {
                            if (int.Parse(match.Groups[3].Value) > STEM_BOUNDARY)
                            {
                                stemmingRules[match.Groups[1].Value] = match.Groups[2].Value;
                            }
                        }
                    }
                }
            }
        }

        public string Stem(string word)
        {
            Match match = Regex.Match(word, @"[^аъоуеияю]*[аъоуеияю]", RegexOptions.Compiled);
            if (!match.Success)
            {
                return word;
            }
            for (int i = match.Index + match.Length + 1; i < word.Length; i++)
            {
                string suffix = word.Substring(i);
                if (stemmingRules.ContainsKey(suffix))
                {
                    return word.Substring(0, i) + stemmingRules[suffix];
                }
            }
            return word;
        }
    }
}
